<template>
  <div class="tags-view-container">
    <div class="tags-view-wrapper">
      <div class="tags-view-scroll">
        <router-link
          v-for="tag in visitedViews"
          :key="tag.path"
          :to="tag.path"
          class="tags-view-item"
          :class="{
            active: isActive(tag),
            closable: !isAffix(tag)
          }"
          @contextmenu.prevent="openMenu($event, tag)"
        >
          <!-- 标签内容 -->
          <div class="tag-content">
            <el-icon v-if="tag.meta?.icon" class="tag-icon">
              <component :is="tag.meta.icon" />
            </el-icon>
            <span class="tag-title">{{ tag.meta?.title }}</span>
            <el-icon 
              v-if="!isAffix(tag)"
              class="close-icon"
              @click.prevent.stop="closeSelectedTag(tag)"
            >
              <Close />
            </el-icon>
          </div>
        </router-link>
      </div>
    </div>

    <!-- 右键菜单 -->
    <div 
      v-show="visible" 
      :style="{ left: menuLeft + 'px', top: menuTop + 'px' }" 
      class="contextmenu"
    >
      <div class="menu-item" @click="refreshSelectedTag(selectedTag!)">
        <el-icon><RefreshRight /></el-icon>
        <span>刷新页面</span>
      </div>
      <div 
        v-if="!isAffix(selectedTag)" 
        class="menu-item" 
        @click="closeSelectedTag(selectedTag!)"
      >
        <el-icon><Close /></el-icon>
        <span>关闭当前</span>
      </div>
      <div class="menu-item" @click="closeOthersTags">
        <el-icon><CircleClose /></el-icon>
        <span>关闭其他</span>
      </div>
      <div class="menu-item" @click="closeAllTags">
        <el-icon><FolderDelete /></el-icon>
        <span>关闭所有</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, onBeforeUnmount } from 'vue'
import { useRoute, useRouter, RouteLocationNormalized } from 'vue-router'
import { Close, RefreshRight, CircleClose, FolderDelete } from '@element-plus/icons-vue'

interface TagView extends RouteLocationNormalized {
  title?: string
}

const route = useRoute()
const router = useRouter()

// 访问过的视图
const visitedViews = ref<TagView[]>([
  {
    path: '/dashboard',
    name: 'Dashboard',
    meta: { 
      title: '控制台',
      icon: 'Monitor',
      affix: true 
    }
  } as TagView
])

// 右键菜单相关
const visible = ref(false)
const menuLeft = ref(0)
const menuTop = ref(0)
const selectedTag = ref<TagView | null>(null)

// 判断是否是当前激活的标签
const isActive = (tag: TagView): boolean => {
  return tag.path === route.path
}

// 判断是否是固定标签
const isAffix = (tag: TagView | null): boolean => {
  return !!(tag?.meta?.affix)
}

// 添加访问视图
const addVisitedView = (view: RouteLocationNormalized) => {
  if (visitedViews.value.some(v => v.path === view.path)) return
  
  const tagView: TagView = {
    ...view,
    title: view.meta?.title || 'unknown'
  }
  visitedViews.value.push(tagView)
}

// 删除访问视图
const delVisitedView = (view: TagView) => {
  const index = visitedViews.value.findIndex(v => v.path === view.path)
  if (index > -1) {
    visitedViews.value.splice(index, 1)
  }
}

// 关闭选中标签
const closeSelectedTag = (view: TagView) => {
  delVisitedView(view)
  if (isActive(view)) {
    toLastView()
  }
}

// 关闭其他标签
const closeOthersTags = () => {
  visitedViews.value = visitedViews.value.filter(tag => {
    return isAffix(tag) || tag.path === route.path
  })
}

// 关闭所有标签
const closeAllTags = () => {
  visitedViews.value = visitedViews.value.filter(tag => isAffix(tag))
  toLastView()
}

// 刷新选中标签
const refreshSelectedTag = (view: TagView) => {
  router.replace({
    path: '/redirect' + view.path
  })
}

// 打开右键菜单
const openMenu = (e: MouseEvent, tag: TagView) => {
  const menuMinWidth = 105
  const offsetX = 15
  const offsetY = 5
  
  // 获取可视区域尺寸
  const { innerWidth, innerHeight } = window
  
  // 计算菜单位置
  let left = e.clientX + offsetX
  let top = e.clientY + offsetY
  
  // 确保菜单不会超出右边界
  if (left + menuMinWidth > innerWidth) {
    left = innerWidth - menuMinWidth - offsetX
  }
  
  // 确保菜单不会超出底部边界
  if (top + 200 > innerHeight) {  // 200是估计的菜单高度
    top = innerHeight - 200 - offsetY
  }

  menuLeft.value = left
  menuTop.value = top
  visible.value = true
  selectedTag.value = tag
}

// 关闭右键菜单
const closeMenu = () => {
  visible.value = false
}

// 跳转到最后一个标签
const toLastView = () => {
  const latestView = visitedViews.value.slice(-1)[0]
  if (latestView) {
    router.push(latestView.path)
  } else {
    router.push('/')
  }
}

// 监听路由变化
watch(
  () => route.path,
  () => {
    addVisitedView(route)
  },
  { immediate: true }
)

// 监听点击事件关闭右键菜单
onMounted(() => {
  document.addEventListener('click', closeMenu)
})

onBeforeUnmount(() => {
  document.removeEventListener('click', closeMenu)
})
</script>

<style lang="scss" scoped>
.tags-view-container {
  height: 52px;
  width: 100%;
  background: #fff;
  position: relative;
  padding: 0 16px;
  
  // 顶部光效
  &::before {
    content: '';
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    height: 1px;
    background: #e5e7eb;
  }
  
  .tags-view-wrapper {
    height: 100%;
    display: flex;
    align-items: center;
    gap: 8px;
  }
  
  .tags-view-scroll {
    flex: 1;
    height: 34px;
    display: flex;
    align-items: center;
    overflow-x: auto;
    overflow-y: hidden;
    scrollbar-width: none;
    -ms-overflow-style: none;
    
    &::-webkit-scrollbar {
      display: none;
    }
  }
  
  .tags-view-item {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    height: 34px;
    padding: 0 16px;
    margin: 0 4px;
    color: #64748b;
    font-size: 13px;
    text-decoration: none;
    cursor: pointer;
    position: relative;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    border-radius: 8px;
    background: #f1f5f9;
    
    // 发光边框
    &::before {
      content: '';
      position: absolute;
      inset: 0;
      padding: 1px;
      border-radius: 8px;
      background: #e2e8f0;
      -webkit-mask: 
        linear-gradient(#fff 0 0) content-box, 
        linear-gradient(#fff 0 0);
      mask: 
        linear-gradient(#fff 0 0) content-box, 
        linear-gradient(#fff 0 0);
      -webkit-mask-composite: xor;
      mask-composite: exclude;
    }
    
    // 内容布局
    .tag-content {
      display: flex;
      align-items: center;
      gap: 8px;
      z-index: 1;
      
      .tag-icon {
        font-size: 14px;
        transition: all 0.3s ease;
      }
      
      .tag-title {
        transition: all 0.3s ease;
      }
      
      .close-icon {
        width: 16px;
        height: 16px;
        margin-left: 4px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 4px;
        font-size: 12px;
        opacity: 0.4;
        transform: scale(0.8);
        transition: all 0.3s ease;
        
        &:hover {
          background: rgba(0, 0, 0, 0.15);
          transform: scale(1.1);
          opacity: 1;
        }
      }
    }
    
    // 悬停效果
    &:hover {
      transform: translateY(-1px);
      color: var(--el-color-primary-dark-2);
      background: var(--el-color-primary-light-9);
      
      &::before {
        background: linear-gradient(
          120deg,
          var(--el-color-primary-light-5),
          var(--el-color-primary),
          var(--el-color-primary-light-5)
        );
        animation: border-shine 2s linear infinite;
      }
      
      .tag-content {
        .tag-icon {
          transform: rotate(15deg) scale(1.2);
        }
        
        .close-icon {
          opacity: 0.6;
          transform: scale(1);
        }
      }
    }
    
    // 激活状态
    &.active {
      color: var(--el-color-primary);
      background: linear-gradient(
        135deg,
        rgba(var(--el-color-primary-rgb), 0.1),
        rgba(var(--el-color-primary-rgb), 0.15)
      );
      font-weight: var(--el-menu-item-font-weight);
      box-shadow: 
        0 2px 8px rgba(var(--el-color-primary-rgb), 0.15),
        inset 0 1px 2px rgba(255, 255, 255, 0.5);
      
      &::before {
        background: linear-gradient(
          to right,
          var(--el-color-primary-light-5),
          var(--el-color-primary),
          var(--el-color-primary-light-5)
        );
        opacity: 0.8;
      }
      
      .tag-content {
        .tag-icon {
          color: var(--el-color-primary);
          transform: scale(1.1);
        }
        
        .tag-title {
          font-weight: 500;
          background: linear-gradient(
            to right,
            var(--el-color-primary),
            var(--el-color-primary-light-3)
          );
          -webkit-background-clip: text;
          -webkit-text-fill-color: transparent;
        }
        
        .close-icon {
          opacity: 0.8;
          &:hover {
            background: rgba(var(--el-color-primary-rgb), 0.2);
            opacity: 1;
            transform: scale(1.1) rotate(90deg);
          }
        }
      }
    }
  }
}

// 动画关键帧
@keyframes border-shine {
  0% {
    background-position: 0% center;
  }
  100% {
    background-position: 200% center;
  }
}

// 右键菜单动画
@keyframes menu-pop {
  from {
    opacity: 0;
    transform: scale(0.8) translateY(-10px);
  }
  to {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
}

// 右键菜单样式
.contextmenu {
  position: fixed;
  background: rgba(255, 255, 255, 0.98);
  backdrop-filter: blur(8px);
  border-radius: 12px;
  padding: 6px;
  min-width: 160px;
  box-shadow: 
    0 4px 16px rgba(0, 0, 0, 0.1),
    0 0 0 1px rgba(255, 255, 255, 0.5) inset;
  z-index: 3000;
  animation: menu-pop 0.2s ease;
  
  .menu-item {
    padding: 10px 16px;
    margin: 2px;
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 13px;
    color: #475569;
    cursor: pointer;
    border-radius: 8px;
    transition: all 0.2s ease;
    
    .el-icon {
      font-size: 16px;
      transition: transform 0.2s ease;
    }
    
    &:hover {
      color: var(--el-color-primary);
      background: var(--el-color-primary-light-9);
      transform: translateX(2px);
      
      .el-icon {
        transform: scale(1.2) rotate(15deg);
      }
    }
  }
}
</style> 